package com.itheima.model.common.interceptors;


import com.itheima.model.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取请求的用户信息
 */
public class UserInfoInterceptors implements HandlerInterceptor {

    /**
     * 请求拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取用户信息
        String userInfo = request.getHeader("user-info");
        // 将用户信息存入上下文
        if (userInfo != null && !userInfo.isEmpty()){
            UserContext.setUser(Long.valueOf(userInfo));
        }
        // 放行
        return true;
    }

    /**
     * 请求完成拦截器
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
